package sdp.group14.management;

import static sdp.group14.appdata.HousingSQLiteOpenHelper.*;
import sdp.group14.appdata.AppDataReader;
import sdp.group14.appdata.AppEnumData;
import sdp.group14.appdata.Category;
import sdp.group14.appdata.Event;
import sdp.group14.appdata.HousingSQLiteOpenHelper;
import sdp.group14.appdata.Request;
import sdp.group14.appdata.Room;
import sdp.group14.communication.ServerConnection;

import java.util.ArrayList;

import android.app.Application;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

/**
 * this class is to connect the database and operate all the
 * data reading, writing function between the database and 
 * the list view adapter
 * @author ste706
 *
 */
public class HousingManagerApplication extends Application {

	private SQLiteDatabase database;	
	private AppDataReader appDataReader;
	
	private ArrayList<Request> currentRequests;
	private ArrayList<Event> currentEvents;
	private ArrayList<Category> currentCategories;
	private ArrayList<Room> currentRooms;

	/** Called when the activity is first created. */
	@Override
	public void onCreate() {
		super.onCreate();
		Log.i("database", "loading database");
		
		//HousingSQLiteOpenHelper helper = new HousingSQLiteOpenHelper(this);
		//database = helper.getWritableDatabase();
		
		appDataReader = new AppDataReader();
		
		if (null == currentEvents) {
			loadEvents();
		}
	}

	/**
	 * close the database when the application is terminated
	 */
	@Override
	public void onTerminate() {
		database.close();
		super.onTerminate();
	}

	/**
	 * set the Requests equals to the given Requests array
	 * @param currentRequests
	 */
	public void setCurrentRequests(ArrayList<Request> currentRequests) {
		this.currentRequests = currentRequests;
	}
	
	public void setCurrentEvents(ArrayList<Event> currentEvents) {
		this.currentEvents = currentEvents;
	}

	/**
	 * get all the Requests in the Requests array
	 * @return
	 */
	public ArrayList<Request> getCurrentRequests() {		
		return currentRequests;
	}
	
	public ArrayList<Event> getCurrentEvents() {		
		return currentEvents;
	}

	public Request getRequestById(long id)
	{
		int i = 0;
		for(int j=0; j<currentRequests.size();j++)
		{
			if(currentRequests.get(j).getReqID()==id)
				i = j;
		}
		return currentRequests.get(i);
	}
	
	public Event getEventtById(long id)
	{
		int i = 0;
		for(int j=0; j<currentEvents.size();j++)
		{
			if(currentEvents.get(j).getEventID()==id)
				i = j;
		}
		return currentEvents.get(i);
	}
	
	public int getEventPosition(Event event)
	{
		for(int j=0; j<currentEvents.size();j++)
		{
			if(currentEvents.get(j).getEventID() == event.getEventID())
				return j;
		}
		return -1;
	}

	
	

	public int getRequestPosition(Request request)
	{
		for(int j=0; j<currentRequests.size();j++)
		{
			if(currentRequests.get(j).getReqID() == request.getReqID())
				return j;
		}
		return -1;
	}
	
	/**
	 * add the Request to the database
	 * @param t
	 */
	public void addEvent(Event e) {
		assert(null != e);		
		try
		{
//			Log.e("HousingManagerApplication","mark");
//		int categoryID = getCategoryIDByName(e.getCategory());		
			int categoryID = 1;
			int statusID = getStatusIDByName(e.getStatus());
		
		Event event = new Event(e.getEntryID(), e.getAllowStaffEnter(), statusID,categoryID,
				e.getDescription(), e.getCause(), e.getComments(),
				e.getEventDate(), e.getDayModified(), e.getDayCreated());
		String result = appDataReader.addNewEvent(AppEnumData.ADD_MAINTAINENCE_REQUEST, event);
		loadEvents();
		}
		catch(Exception error)
		{
			Log.e("HousingManagerApplication",e.toString());
		}
		
	}
	
	private int getStatusIDByName(String status)
	{
		if(status.equals("NEW"))
			return AppEnumData.EVENT_STATUS_NEW;
		else if(status.equals("ONGOING"))
			return AppEnumData.EVENT_STATUS_ONGOING;
		else 
			return AppEnumData.EVENT_STATUS_COMPLETED;
	}
	
	private int getCategoryIDByName(String category)
	{		
		for(int i = 0; i < currentCategories.size(); i++)
		{
			if(currentCategories.get(i).getCategory().equals(category))
					return currentCategories.get(i).getCategoryID();
		}
		return -1;
	}


	/**
	 * add the Request to the database
	 * @param t
	 */
	public void addRequest(Request r) {
		assert(null != r);

		ContentValues values = new ContentValues();
		values.put(REQUEST_DATE, r.getreqDate());
		values.put(REQUEST_STATUS, r.getreqStatus());
		values.put(REQUEST_CATEGORY, r.getreqCategory());
		values.put(REQUEST_CAUSE, r.getreqCause());
		values.put(REQUEST_DESCRIPTION, r.getreqDescription());
		values.put(REQUEST_COMMENT, r.getreqComment());
		values.put(REQUEST_ALLOW_ENTER, r.isReqAllowEnter());
		r.setReqID(database.insert(REQUESTS_TABLE, null, values));
		Log.e("database",""+r.getReqID());
		currentRequests.add(r);
	}


	/**
	 * update the Request to the database
	 * @param t
	 */
	public void updateRequest(Request r) {
		assert(null != r);

		try
		{
			ContentValues values = new ContentValues();
			values.put(REQUEST_DATE, r.getreqDate());
			values.put(REQUEST_STATUS, r.getreqStatus());
			values.put(REQUEST_CATEGORY, r.getreqCategory());
			values.put(REQUEST_CAUSE, r.getreqCause());
			values.put(REQUEST_DESCRIPTION, r.getreqDescription());
			values.put(REQUEST_COMMENT, r.getreqComment());
			values.put(REQUEST_ALLOW_ENTER, r.isReqAllowEnter());
			String filter = "" +  REQUEST_ID + "="+ r.getReqID();
			database.update(REQUESTS_TABLE, values,filter, null);
			//insert(REQUESTS_TABLE, null, values));
			Log.e("database","update requestID:"+r.getReqID());
			currentRequests.set(getRequestPosition(r), r);
		}
		catch(Exception e)
		{
			Log.e("database","error occurs in updating request");
		}
	}

	/**
	 * delete the given Request in the database
	 */
	public void deleteRequest(Long id) {
		try
		{
		String where = String.format("%s == (%s)", REQUEST_ID, id);
		database.delete(REQUESTS_TABLE, where, null);
		}
		catch(Exception e)
		{
			Log.e("database", "errors occured in deleting request");
		}
	}
	
	/**
	 * delete the given Event in the database
	 */
	public void deleteEvent(Long id) {
		try
		{
		String where = String.format("%s == (%s)", REQUEST_ID, id);
		database.delete(REQUESTS_TABLE, where, null);
		}
		catch(Exception e)
		{
			Log.e("database", "errors occured in deleting request");
		}
	}

	/**
	 * delete all the Requests in the database
	 */
	public void deleteAllRequests()
	{
		database.delete(HousingSQLiteOpenHelper.REQUESTS_TABLE, null, null);
	}
	
	/**
	 * delete all the Requests in the database
	 */
	public void deleteAllEvents()
	{
		database.delete(HousingSQLiteOpenHelper.REQUESTS_TABLE, null, null);
	}

	/**
	 * save all the Requests in the Requests array into the database
	 * @param t
	 */
	public void saveRequest(Request r) {
		assert(null != r);
		ContentValues values = new ContentValues();
		values.put(REQUEST_DATE, r.getreqDate());
		values.put(REQUEST_STATUS, r.getreqDate());
		values.put(REQUEST_CATEGORY, r.getreqDate());
		values.put(REQUEST_DESCRIPTION, r.getreqDate());
		values.put(REQUEST_COMMENT, r.getreqDate());
		values.put(REQUEST_ALLOW_ENTER, r.getreqDate());	
		long id = r.getReqID();
		String where = String.format("%s = %d", REQUEST_ID, id);

		database.update(REQUESTS_TABLE, values, where, null);
	}

	/**
	 * load all the Events from database when the application is
	 * first initialized
	 */	
	private void loadEvents() {
		try
		{
			currentEvents = new ArrayList<Event>();
			Log.i("HousingManagerApplication", "loading events");
			String entryID = "1";
			currentEvents = (ArrayList<Event>)appDataReader.getAllMaintainenceRequest(entryID, AppEnumData.GET_ALL_MAINTAINENCE_REQUEST);
		}
		catch (Exception e)
		{
			Log.e("HousingManagerApplication","errors occurs in loading events");
		}
	}
	
	
	/**
	 * load all the Categories from database when the application is
	 * first initialized
	 */	
	private void loadCategories() {
		try
		{
			currentCategories = new ArrayList<Category>();
			Log.i("HousingManagerApplication", "loading categories");
			String entryID = "1";
			currentCategories = appDataReader.getAllCategories(entryID, AppEnumData.GET_ALL_CATEGORIES);
		}
		catch (Exception e)
		{
			Log.e("HousingManagerApplication","errors occurs in loading categories");
		}
	}
	
	
	/**
	 * load all the Rooms from database when the application is
	 * first initialized
	 */	
	private void loadRooms() {
		try
		{
			currentRooms = new ArrayList<Room>();
			Log.i("HousingManagerApplication", "loading rooms");
			String entryID = "1";
			currentRooms = appDataReader.getAllRooms(entryID, AppEnumData.GET_ALL_ROOMS);
		}
		catch (Exception e)
		{
			Log.e("HousingManagerApplication","errors occurs in loading rooms");
		}	
	}
}
